package com.cyh.pangu.offer;

import java.util.HashMap;
import java.util.Map;

public class Offer39 {

    public int majorityElement(int[] nums) {
        int count = 1, cur = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (cur == nums[i]) {
                count++;
            } else{
                count--;
                if (count == 0) {
                    cur = nums[i];
                    count = 1;
                }
            }
        }
        return cur;
    }

    public int majorityElement_2(int[] nums) {
        int count = 1, cur = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (cur != nums[i]) {
                --count;
                if (count == 0) {
                    cur = nums[i];
                    count = 1;
                }
            } else {
                count++;
            }
        }
        return cur;
    }

    public static void main(String[] args) {
        int[] nums = {2,1,2,3,2,5,2,4,2};
        Offer39 offer39 = new Offer39();
        int num = offer39.majorityElement(nums);
        System.out.println("num:" + num);
    }

}
